﻿package com.adsame.core
{
	import com.adsame.adapters.*;
	import com.adsame.interfaces.*;
	import com.adsame.views.*;
	import com.adsame.utils.*;

	/**
	 * AsamViewManager 
	 * 
	 * @package 
	 * @version $id$
	 * @copyright Powered By Adsame 2008-2009 (c)
	 * @author olga 
	 * @license 
	 */
	public class AsamViewManager
	{
		/**
		 * traversalNode 
		 * 
		 * @param node : XML $node : XML 
		 * @param view : IAsamView $view : IAsamView 
		 * @static
		 * @access public
		 * @return void
		 */
		public static function traversalNode(node : XML, view : IAsamView) : IAsamView
		{
			if (node.nodeKind() == "element")
			{
				/**
				 * 根据节点的标签名字来判断标签如何被处理
				 */
				if (node.name() == "ad_view")
				{
					var view_old = view;
					var view : IAsamView = AsamViewManager.factory(node.attribute("type"));
					if (view_old)
					{
						view.appendTo(view_old);
					}
				}
				else if (node.name() == "attrs")
				{
					view.create(AsamXml2ObjectAdapter.parse(node));
				}
				else if (node.name() == "events")
				{
					view.event(AsamXml2ObjectAdapter.parse(node));
				}

				/**
				 * 如果是容器节点或者容器的子容器标签，则继续循环子标签
				 */
				if (node.name() == "ad_view" || node.name() == "children") 
				{
					for (var i = 0; i < node.children().length(); i++)
					{
						AsamViewManager.traversalNode(node.children()[i], view);
					}
				}
			}
			/* else if (node.nodeKind() == 'text') { return; } */

			return view;
		}

		/**
		 * buildViewMap 
		 * 
		 * @param view_map : XML $view_map : XML 
		 * @static
		 * @access public
		 * @return void
		 */
		public static function buildViewMap(view_map : XML) : IAsamIterator
		{
			if (view_map.nodeKind() != "element" || view_map.name() != "view_root")
			{
				return null;
			}
			else
			{
				var view_iterator = new AsamIterator();
				var length : int = view_map.children().length();
				for (var i = 0; i < length; i++)
				{
					var node : XML = view_map.children()[i];
					var view : IAsamView = AsamViewManager.traversalNode(node, null);
					view_iterator.add(view, view.getName());
				}
				return view_iterator;
			}
		}

		/**
		 * factory 
		 * 
		 * @param view_type : String $view_type : String 
		 * @static
		 * @access public
		 * @return void
		 */
		public static function factory(view_type : String) : IAsamView
		{
			switch (view_type) {
				case "rect_view":
					return new AsamSimpleView();
					break;
				default:
					return null;
			}
		}
	}
}
